package com.timothy.service;

import java.lang.reflect.Method;

import com.android.internal.telephony.ITelephony;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.util.Log;

public class CallAndSMSInterceptor extends Service {
	//要拦截的号码
	private final static String BLOCKED_NUMBER = "051262921081";
	private IncomingCallReceiver mIncomingCallReceiver;
    private ITelephony mITelephony;
    private AudioManager mAudioManager;
    
	//占线时转移，这里13800000000是空号，所以会提示所拨的号码为空号
    private final String ENABLE_SERVICE = "tel:**67*13800000000%23";
    private final String DISABLE_SERVICE = "tel:%23%2367%23";
    
	private final static int OP_REGISTER = 100;
	private final static int OP_CANCEL = 200;
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		
		mIncomingCallReceiver = new IncomingCallReceiver();
        
		IntentFilter mIntentFilter = new IntentFilter();
		//拦截电话
		mIntentFilter.addAction("android.intent.action.PHONE_STATE");
		//拦截短信
		mIntentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
		
		//注册BroadcastReceiver
        registerReceiver(mIncomingCallReceiver, mIntentFilter);	
        
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        
        //利用反射获取隐藏的endcall方法
        TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        
		try {
			Method getITelephonyMethod = TelephonyManager.class.getDeclaredMethod("getITelephony", (Class[]) null);
			getITelephonyMethod.setAccessible(true);
			mITelephony = (ITelephony) getITelephonyMethod.invoke(mTelephonyManager, (Object[]) null);
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
	    
	    //设置呼叫转移
        Message message = mHandler.obtainMessage();
		message.what = OP_REGISTER;
		mHandler.dispatchMessage(message);
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		return super.onStartCommand(intent, flags, startId);
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
		//取消呼叫转移
        Message message = mHandler.obtainMessage();
		message.what = OP_CANCEL;
		mHandler.dispatchMessage(message);
	}
	
    //定义Handler
    private Handler mHandler = new Handler() {
		public void handleMessage(Message response) {
	    	int what = response.what;	    	
	    	switch(what) {
		    	case OP_REGISTER:{
		    		Intent i = new Intent(Intent.ACTION_CALL);
		            i.setData(Uri.parse(ENABLE_SERVICE));
		            startActivity(i);
		    		break;
		    	}
		    	case OP_CANCEL:{
		    		Intent i = new Intent(Intent.ACTION_CALL);
		            i.setData(Uri.parse(DISABLE_SERVICE));
		            startActivity(i);
		    		break;
		    	}
	    	}
		}
    };
	
	private class IncomingCallReceiver extends BroadcastReceiver{
		
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			Log.d("mayingcai", "Action:" + action);
			
			if("android.intent.action.PHONE_STATE".equals(action)){//拦截电话
				String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
		        Log.i("mayingcai", "State: "+ state);
				String number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
		        Log.d("mayingcai", "Incomng Number: " + number);
		        
		        if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING)){//电话正在响铃
		        	if(number.equals(BLOCKED_NUMBER)){//拦截指定的电话号码
		        		//先静音处理
		    	    	mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
		    	    	Log.d("mayingcai", "Turn Ringtone Silent");
		        		try {
		        			//挂断电话
							mITelephony.endCall();
						} catch (Exception e) {
							e.printStackTrace();
						}
						//再恢复正常铃声
		                mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
		        	}
		        }
			}else if("android.provider.Telephony.SMS_RECEIVED".equals(action)){//拦截短信
				SmsMessage sms = getMessagesFromIntent(intent)[0];
				String number = sms.getOriginatingAddress();
				Log.d("mayingcai", "Incomng Number: " + number);
				number = trimSmsNumber("+86", number);//把国家代码去除掉
				if(number.equals(BLOCKED_NUMBER)){
					abortBroadcast();//这句很重要，中断广播后，其他要接收短信的应用都没法收到短信广播了
				}
			}
		}
	}
	
	//获取短消息
    public final static SmsMessage[] getMessagesFromIntent(Intent intent) {
        Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
        byte[][] pduObjs = new byte[messages.length][];
        for (int i = 0; i < messages.length; i++) {
            pduObjs[i] = (byte[]) messages[i];
        }
        byte[][] pdus = new byte[pduObjs.length][];
        int pduCount = pdus.length;
        SmsMessage[] msgs = new SmsMessage[pduCount];
        for (int i = 0; i < pduCount; i++) {
            pdus[i] = pduObjs[i];
            msgs[i] = SmsMessage.createFromPdu(pdus[i]);
        }
        return msgs;
    }
    
    //去处号码前缀
    public final static String trimSmsNumber(String prefix, String number){
		String s = number;
		if(prefix.length()>0 && number.startsWith(prefix)){
			s = number.substring(prefix.length());
		}
		return s;
	}
	
}
